package com.lsq.spring;

import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.*;

/**
 * @author lsq
 * @description springbean容器
 * @date 2023/9/5
 */
public class LsqApplicationContext {
    private Class configClass;

    private Map<String, BeanDefinition> beanDefinitionMap = new HashMap<>();//《类名，类属性》

    private Map<String, Object> singletonObjects = new HashMap<>();//单例池

    private List<BeanPostProcessor> beanPostProcessors = new ArrayList<>();

    public LsqApplicationContext(Class configClass) {
        this.configClass = configClass;
        //扫描创建beanDefinitionMap
        scan(configClass);
        //实例化单例放入singletonObjects
        creatSingletonBean();
    }


    private void creatSingletonBean() {
        for (Map.Entry<String, BeanDefinition> entry : beanDefinitionMap.entrySet()) {
            BeanDefinition beanDefinition = entry.getValue();
            String beanName = entry.getKey();
            if (beanDefinition.getScope().equals("singleton")){
                Object bean = creatBean(beanName, beanDefinition);
                singletonObjects.put(beanName, bean);
            }
        }
    }

    private Object creatBean(String beanName, BeanDefinition beanDefinition){
        try {

            Class clazz = beanDefinition.getClazz();
            Object instance = clazz.newInstance();

            //依赖注入实例化
            for (Field declaredField : clazz.getDeclaredFields()) {
                if (declaredField.isAnnotationPresent(Autowired.class)){
                    Object bean = getBean(declaredField.getName());
                    declaredField.setAccessible(true);
                    declaredField.set(instance, bean);
                }
            }
            //初始化
            //postProcessBeforeInitialization
            for (BeanPostProcessor beanPostProcessor : beanPostProcessors) {
                instance = beanPostProcessor.postProcessBeforeInitialization(instance, beanName);
            }

            if (instance instanceof InitializingBean){ //初始化对属性赋值
                ((InitializingBean)instance).afterPropertiesSet();
            }

            //postProcessAfterInitialization
            for (BeanPostProcessor beanPostProcessor : beanPostProcessors) {
                instance = beanPostProcessor.postProcessAfterInitialization(instance, beanName);
            }

            return instance;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return null;
    }


    private void scan(Class configClass) {
        //解析传入配置类，拿到注解扫描路径
        ComponentScan componentScan = (ComponentScan) configClass.getAnnotation(ComponentScan.class);
        String path = componentScan.value();
        path = path.replace(".", "/");

        //扫描路径有注解component的类后生成对象
        ClassLoader classLoader = LsqApplicationContext.class.getClassLoader(); //appclassloader类加载器加载target/classes文件夹
        URL resource = classLoader.getResource(path);

        File file = new File(resource.getFile());
        File[] files = file.listFiles();
        for (File f : files) {
            String absolutePath = f.getAbsolutePath();
            if (absolutePath.endsWith(".class")) {
                String className = absolutePath.substring(absolutePath.indexOf("com"), absolutePath.indexOf(".class"));
                className = className.replace("\\", ".");

                try {
                    Class clazz = classLoader.loadClass(className);

                    if (clazz.isAnnotationPresent(Component.class)) {

                        //添加后置处理器bean
                        if (BeanPostProcessor.class.isAssignableFrom(clazz)) {
                            BeanPostProcessor o = (BeanPostProcessor) clazz.newInstance();
                            beanPostProcessors.add(o);
                        }

                        Component component = (Component) clazz.getAnnotation(Component.class);
                        String beanName = component.value();

                        BeanDefinition beanDefinition = new BeanDefinition();

                        beanDefinition.setClazz(clazz);
                        if (clazz.isAnnotationPresent(Scope.class)){
                            Scope scope = (Scope) clazz.getAnnotation(Scope.class);
                            beanDefinition.setScope(scope.value());//多例
                        } else {
                            beanDefinition.setScope("singleton");//单例
                        }

                        beanDefinitionMap.put(beanName, beanDefinition);

                    }

                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (InstantiationException e) {
                    throw new RuntimeException(e);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    public Object getBean(String benaName) { //拿到beandefinition 判断是否单列
        if (beanDefinitionMap.containsKey(benaName)){
            BeanDefinition beanDefinition = beanDefinitionMap.get(benaName);
            if (beanDefinition.getScope().equals("singleton")){
                //单例
                Object o = singletonObjects.get(benaName);
                return o;
            }else {//多例
                Object bean = creatBean(benaName, beanDefinition);
                return bean;
            }
        } else {
            throw new NullPointerException();
        }
    }
}
